import store from './store/index'
import music from './store/music'
import nm from './sdk/index'
import { createRoute } from './route/index'
import { getCanvas, getCtx } from '../ctx'
/**
 * 游戏主函数控制
 */
export const control = {
  mainExe: null
}
/**
 * 游戏主函数
 */
export default class Main {
  constructor(ctx = getCtx()) {
    if (control.mainExe) {
      control.mainExe.restart()
      return control.mainExe
    }
    createRoute()
    this.ctx = ctx
    this.init(ctx)
    this.aniId = 0
    this.restart()
    control.mainExe = this
  }
  init () {
    const canvas = getCtx().canvas
    if (!canvas) {
      return
    }
  }

  restart() {
    const canvas = getCtx().canvas
    if (!canvas) {
     return 
    }
    this.store = store
    store.reset()
    nm.restart()
    this.bindLoop = this.loop.bind(this)
    this.hasEventBind = false
    // 清除上一局的动画
    window.cancelAnimationFrame(this.aniId)
    this.aniId = window.requestAnimationFrame(
      this.bindLoop,
      canvas
    )
  }
  /**
   * 卸载
  */
  destroy() {
    nm.destroy()
  }
  /**
   * canvas重绘函数
   * 每一帧重新绘制所有的需要展示的元素
   */
  render() {
    const ctx = getCtx()
    ctx.clearRect(0, 0, getCanvas().width, getCanvas().height)
    nm.render()
  }

  // 游戏逻辑更新主函数
  update() {
    nm.update()
  }
  // 实现游戏帧循环
  loop() {
    store.frame++

    this.update()
    this.render()

    this.aniId = window.requestAnimationFrame(
      this.bindLoop,
      getCtx().canvas
    )
  }
}
/**
 * 创建游戏
 */
export const createdGame = function (ctx) {
  if (control.mainExe) {
    control.mainExe.restart()
    return control.mainExe
  }
  control.mainExe = new Main(ctx)
  return control.mainExe
}
/**
 * 卸载游戏
 */
export const destroyGame = () => {
  control.mainExe.destroy()
  control.mainExe = null 
  store.reset()
}
/**
 * 获取实例
 */
export const getGame = () => {
  return control.mainExe
}
/**
 * 关闭音乐
 */
export const closeMusic = () => {
  music.close()
}